import { functionList } from './functions';
(function(mod) {
  mod(require('codemirror'));
})(function(CodeMirror) {
  const functionKeys = [];
  functionList.forEach(i => {
    i.children.forEach(j => {
      functionKeys.push(j.name);
    });
  });
  CodeMirror.registerHelper('hint', 'formula', function(editor, options) {
    const keywords = functionKeys;
    const cur = editor.getCursor();
    const curLine = editor.getLine(cur.line);
    const curWordData = getCurWords(curLine, cur.ch - 1);
    const curWord = curWordData.word.toUpperCase();
    const start = curWordData.start;
    const end = curWordData.end;
    const list = keywords.filter(key => {
      return key.startsWith(curWord);
    });
    return { list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end) };
  });
});

function getCurWords(string, index) {
  if (index < 0) return { word: string, start: 0, end: 0 };
  let start = index;
  let end = index;
  const empty = /\s/g;
  while (string[start] && !empty.test(string[start]) && string[start] !== '(') {
    start--;
  }
  while (string[end] && !empty.test(string[end]) && string[end] !== ')') {
    end++;
  }
  return {
    word: string.slice(start + 1, end),
    start: start + 1,
    end: end
  };
}
